//
//  YHSpeechSynthesizer.swift
//  YHKit
//
//  Created by amovision on 2025/9/15.
//

import AVFoundation

public class YHSpeechSynthesizer: NSObject {
  
  // MARK: - Singleton
  public static let shared = YHSpeechSynthesizer()

  override private init() {
    super.init()
  }

  // MARK: - Properties

  private let synthesizer = AVSpeechSynthesizer()

  // MARK: - Public Methods

  /// 播报一段文本
  /// - Parameter message: 要播报的文本
  public func speak(_ message: String) {
    // 如果正在播报，先停止
    stopSpeaking()

    let utterance = AVSpeechUtterance(string: message)

    // 根据系统首选语言自动选择语音
//    let preferredLanguage = Locale.preferredLanguages.first ?? "en"
//
//    if preferredLanguage.contains("-Han") {
//      utterance.voice = AVSpeechSynthesisVoice(language: "zh-CN")
//    } else {
//      // 如果不是中文，使用系统默认的英文语音
//      utterance.voice = AVSpeechSynthesisVoice(language: "en")
//    }
    utterance.voice = AVSpeechSynthesisVoice(language: "en")
    // 开始播报
    synthesizer.speak(utterance)
  }

  /// 停止播报
  public func stopSpeaking() {
    if synthesizer.isSpeaking {
      synthesizer.stopSpeaking(at: .immediate)
    }
  }
}
